#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sqlite3.h>
#include <ctype.h>

// 账号类型枚举
typedef enum {
    ACCOUNT_TYPE_STUDENT = 0,  // 学生账号
    ACCOUNT_TYPE_ADMIN = 1     // 管理员账号
} AccountType;

// 数据库连接对象
sqlite3 *db;

// 错误处理函数
void handle_error(const char *msg, int rc) {
    if (rc != SQLITE_OK) {
        fprintf(stderr, "%s: %s\n", msg, sqlite3_errmsg(db));
    }
}

// 密码复杂度验证
int validate_password(const char *password) {
    if (!password || strlen(password) < 8) {
        printf("密码长度至少为8位！\n");
        return 0;
    }
    
    int has_upper = 0, has_lower = 0, has_digit = 0;
    for (int i = 0; password[i]; i++) {
        if (isupper(password[i])) has_upper = 1;
        else if (islower(password[i])) has_lower = 1;
        else if (isdigit(password[i])) has_digit = 1;
    }
    
    if (!has_upper) printf("密码必须包含大写字母！\n");
    if (!has_lower) printf("密码必须包含小写字母！\n");
    if (!has_digit) printf("密码必须包含数字！\n");
    
    return has_upper && has_lower && has_digit;
}

// 密码加密
void encrypt_password(const char *password, char *encrypted) {
    int i = 0;
    while (password[i]) {
        encrypted[i] = password[i] + 10; // 简单加密
        i++;
    }
    encrypted[i] = '\0';
}

// 安全输入
int safe_input(char *buffer, int max_len, const char *prompt) {
    printf("%s", prompt);
    if (fgets(buffer, max_len, stdin)) {
        buffer[strcspn(buffer, "\n")] = 0;
        return 1;
    }
    return 0;
}

// 创建用户函数
int create_user(const char *username, const char *password, AccountType account_type, const char *user_info) {
    sqlite3_stmt *stmt;
    const char *sql = "INSERT INTO Users(username, password, account_type, user_info) VALUES(?, ?, ?, ?)";
    int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, 0);
    if (rc != SQLITE_OK) return rc;

    sqlite3_bind_text(stmt, 1, username, -1, SQLITE_STATIC);
    sqlite3_bind_text(stmt, 2, password, -1, SQLITE_STATIC);
    sqlite3_bind_int(stmt, 3, account_type);
    sqlite3_bind_text(stmt, 4, user_info, -1, SQLITE_STATIC);

    rc = sqlite3_step(stmt);
    sqlite3_finalize(stmt);
    return rc;
}

// 用户登录函数
int user_login(const char *username, const char *password, AccountType *account_type) {
    sqlite3_stmt *stmt;
    const char *sql = "SELECT account_type FROM Users WHERE username=? AND password=?";
    int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, 0);
    if (rc != SQLITE_OK) return rc;

    sqlite3_bind_text(stmt, 1, username, -1, SQLITE_STATIC);
    sqlite3_bind_text(stmt, 2, password, -1, SQLITE_STATIC);

    rc = sqlite3_step(stmt);
    if (rc == SQLITE_ROW) {
        *account_type = sqlite3_column_int(stmt, 0);
        sqlite3_finalize(stmt);
        return 1;
    }
    sqlite3_finalize(stmt);
    return 0;
}

// 修改用户信息函数
int update_user_info(const char *username, const char *new_info) {
    sqlite3_stmt *stmt;
    const char *sql = "UPDATE Users SET user_info =? WHERE username =?";
    int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, 0);
    if (rc != SQLITE_OK) return rc;

    sqlite3_bind_text(stmt, 1, new_info, -1, SQLITE_STATIC);
    sqlite3_bind_text(stmt, 2, username, -1, SQLITE_STATIC);

    rc = sqlite3_step(stmt);
    sqlite3_finalize(stmt);
    return rc;
}

// 修改用户密码函数
int update_user_password(const char *username, const char *new_password) {
    char encrypted[100];
    encrypt_password(new_password, encrypted);
    
    sqlite3_stmt *stmt;
    const char *sql = "UPDATE Users SET password =? WHERE username =?";
    int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, 0);
    if (rc != SQLITE_OK) return rc;

    sqlite3_bind_text(stmt, 1, encrypted, -1, SQLITE_STATIC);
    sqlite3_bind_text(stmt, 2, username, -1, SQLITE_STATIC);

    rc = sqlite3_step(stmt);
    sqlite3_finalize(stmt);
    return rc;
}

// 查询所有用户函数
void query_all_users() {
    sqlite3_stmt *stmt;
    const char *sql = "SELECT id, username, account_type, user_info FROM Users";
    int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, 0);
    if (rc != SQLITE_OK) {
        handle_error("查询用户失败", rc);
        return;
    }

    printf("\n所有用户列表：\n");
    printf("ID\t用户名\t\t账号类型\t用户信息\n");
    printf("---------------------------------------------\n");

    while ((rc = sqlite3_step(stmt)) == SQLITE_ROW) {
        int id = sqlite3_column_int(stmt, 0);
        const unsigned char *username = sqlite3_column_text(stmt, 1);
        int account_type = sqlite3_column_int(stmt, 2);
        const unsigned char *user_info = sqlite3_column_text(stmt, 3);

        printf("%d\t%s\t\t%s\t%s\n", 
               id, 
               username, 
               account_type == ACCOUNT_TYPE_ADMIN ? "管理员" : "学生", 
               user_info ? (const char *)user_info : "无");
    }

    if (rc != SQLITE_DONE) {
        handle_error("查询用户过程中出错", rc);
    }

    sqlite3_finalize(stmt);
}

// 管理员专用函数：删除用户
int delete_user(const char *username) {
    sqlite3_stmt *stmt;
    const char *sql = "DELETE FROM Users WHERE username =?";
    int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, 0);
    if (rc != SQLITE_OK) return rc;

    sqlite3_bind_text(stmt, 1, username, -1, SQLITE_STATIC);

    rc = sqlite3_step(stmt);
    sqlite3_finalize(stmt);
    return rc;
}

// 管理员专用函数：修改用户账号类型
int change_user_account_type(const char *username, AccountType new_type) {
    sqlite3_stmt *stmt;
    const char *sql = "UPDATE Users SET account_type =? WHERE username =?";
    int rc = sqlite3_prepare_v2(db, sql, -1, &stmt, 0);
    if (rc != SQLITE_OK) return rc;

    sqlite3_bind_int(stmt, 1, new_type);
    sqlite3_bind_text(stmt, 2, username, -1, SQLITE_STATIC);

    rc = sqlite3_step(stmt);
    sqlite3_finalize(stmt);
    return rc;
}

// 主函数 - 用于调试用户管理模块
int main() {
    int rc = sqlite3_open("user_test.db", &db);
    if (rc != SQLITE_OK) {
        handle_error("无法打开数据库", rc);
        return 1;
    }

    // 创建用户表（如果不存在）
    const char *sql_create_users = "CREATE TABLE IF NOT EXISTS Users("
                                   "id INTEGER PRIMARY KEY AUTOINCREMENT,"
                                   "username TEXT UNIQUE NOT NULL,"
                                   "password TEXT NOT NULL,"
                                   "account_type INTEGER DEFAULT 0,"
                                   "user_info TEXT)";
    sqlite3_exec(db, sql_create_users, NULL, NULL, NULL);

    // 创建默认管理员账号（如果不存在）
    sqlite3_stmt *stmt;
    const char *sql_check_admin = "SELECT COUNT(*) FROM Users WHERE account_type = 1";
    rc = sqlite3_prepare_v2(db, sql_check_admin, -1, &stmt, 0);
    if (rc == SQLITE_OK && sqlite3_step(stmt) == SQLITE_ROW) {
        int count = sqlite3_column_int(stmt, 0);
        sqlite3_finalize(stmt);
        
        if (count == 0) {
            char encrypted[100];
            encrypt_password("admin123", encrypted);
            create_user("admin", encrypted, ACCOUNT_TYPE_ADMIN, "系统默认管理员");
            printf("已创建默认管理员账号: 用户名=admin, 密码=admin123\n");
        }
    }

    int choice;
    char username[50], password[50], encrypted[100];
    char user_info[200];
    AccountType account_type;
    int running = 1;
    int is_logged_in = 0;
    char current_username[50] = {0};

    printf("===== 用户管理模块调试程序 =====\n");

    while (running) {
        if (!is_logged_in) {
            printf("\n请选择操作：\n");
            printf("1. 用户注册\n");
            printf("2. 用户登录\n");
            printf("0. 退出程序\n");
            printf("请输入选择：");

            if (scanf("%d", &choice) != 1) {
                printf("无效输入！\n");
                while (getchar() != '\n'); // 清空输入缓冲区
                continue;
            }
            getchar(); // 消耗换行符

            switch (choice) {
                case 1: // 用户注册
                    if (!safe_input(username, sizeof(username), "请输入用户名：")) continue;
                    
                    // 循环输入直到密码满足复杂度要求
                    do {
                        if (!safe_input(password, sizeof(password), "请输入密码(需包含大小写字母和数字，至少8位)：")) continue;
                    } while (!validate_password(password));
                    
                    encrypt_password(password, encrypted);
                    
                    // 新用户默认为学生账号
                    rc = create_user(username, encrypted, ACCOUNT_TYPE_STUDENT, "");
                    if (rc == SQLITE_OK) {
                        printf("学生账号注册成功！\n");
                    } else if (rc == SQLITE_CONSTRAINT) {
                        printf("注册失败：用户名已存在！\n");
                    } else {
                        printf("注册失败：未知错误！\n");
                    }
                    break;
                    
                case 2: // 用户登录
                    if (!safe_input(username, sizeof(username), "请输入用户名：")) continue;
                    if (!safe_input(password, sizeof(password), "请输入密码：")) continue;
                    
                    encrypt_password(password, encrypted);
                    
                    if (user_login(username, encrypted, &account_type)) {
                        printf("登录成功！\n");
                        printf("账号类型：%s\n", account_type == ACCOUNT_TYPE_ADMIN ? "管理员" : "学生");
                        
                        is_logged_in = 1;
                        strcpy(current_username, username);
                    } else {
                        printf("登录失败：用户名或密码错误！\n");
                    }
                    break;
                    
                case 0: // 退出程序
                    running = 0;
                    printf("程序已退出！\n");
                    break;
                    
                default:
                    printf("无效选择，请重新输入！\n");
            }
        } 
        else {
            // 已登录状态
            if (account_type == ACCOUNT_TYPE_ADMIN) {
                // 管理员菜单
                printf("\n===== 管理员菜单 =====\n");
                printf("当前用户: %s\n", current_username);
                printf("请选择操作：\n");
                printf("1. 查询所有用户\n");
                printf("2. 创建新用户\n");
                printf("3. 删除用户\n");
                printf("4. 修改用户账号类型\n");
                printf("5. 修改个人信息\n");
                printf("6. 修改密码\n");
                printf("0. 退出登录\n");
                printf("请输入选择：");

                if (scanf("%d", &choice) != 1) {
                    printf("无效输入！\n");
                    while (getchar() != '\n'); // 清空输入缓冲区
                    continue;
                }
                getchar(); // 消耗换行符

                switch (choice) {
                    case 1: // 查询所有用户
                        query_all_users();
                        break;
                        
                    case 2: // 创建新用户
                        if (!safe_input(username, sizeof(username), "请输入用户名：")) continue;
                        
                        // 循环输入直到密码满足复杂度要求
                        do {
                            if (!safe_input(password, sizeof(password), "请输入密码(需包含大小写字母和数字，至少8位)：")) continue;
                        } while (!validate_password(password));
                        
                        encrypt_password(password, encrypted);
                        
                        printf("请选择账号类型 (0-学生, 1-管理员): ");
                        if (scanf("%d", &choice) != 1) {
                            printf("无效输入！\n");
                            while (getchar() != '\n');
                            continue;
                        }
                        getchar(); // 消耗换行符
                        
                        account_type = (choice == 1) ? ACCOUNT_TYPE_ADMIN : ACCOUNT_TYPE_STUDENT;
                        
                        if (!safe_input(user_info, sizeof(user_info), "请输入用户信息：")) continue;
                        
                        rc = create_user(username, encrypted, account_type, user_info);
                        if (rc == SQLITE_OK) {
                            printf("用户创建成功！\n");
                        } else if (rc == SQLITE_CONSTRAINT) {
                            printf("创建失败：用户名已存在！\n");
                        } else {
                            printf("创建失败：未知错误！\n");
                        }
                        break;
                        
                    case 3: // 删除用户
                        query_all_users();
                        if (!safe_input(username, sizeof(username), "请输入要删除的用户名：")) continue;
                        
                        if (strcmp(username, current_username) == 0) {
                            printf("不能删除当前登录的用户！\n");
                            continue;
                        }
                        
                        rc = delete_user(username);
                        if (rc == SQLITE_OK) {
                            printf("用户删除成功！\n");
                        } else {
                            printf("删除失败：用户不存在或发生错误！\n");
                        }
                        break;
                        
                    case 4: // 修改用户账号类型
                        query_all_users();
                        if (!safe_input(username, sizeof(username), "请输入要修改的用户名：")) continue;
                        
                        if (strcmp(username, current_username) == 0) {
                            printf("不能修改当前登录的用户类型！\n");
                            continue;
                        }
                        
                        printf("请选择新的账号类型 (0-学生, 1-管理员): ");
                        if (scanf("%d", &choice) != 1) {
                            printf("无效输入！\n");
                            while (getchar() != '\n');
                            continue;
                        }
                        getchar(); // 消耗换行符
                        
                        account_type = (choice == 1) ? ACCOUNT_TYPE_ADMIN : ACCOUNT_TYPE_STUDENT;
                        
                        rc = change_user_account_type(username, account_type);
                        if (rc == SQLITE_OK) {
                            printf("用户账号类型修改成功！\n");
                        } else {
                            printf("修改失败：用户不存在或发生错误！\n");
                        }
                        break;
                        
                    case 5: // 修改个人信息
                        if (!safe_input(user_info, sizeof(user_info), "请输入新的个人信息：")) continue;
                        
                        rc = update_user_info(current_username, user_info);
                        if (rc == SQLITE_OK) {
                            printf("个人信息更新成功！\n");
                        } else {
                            printf("更新失败：发生错误！\n");
                        }
                        break;
                        
                    case 6: // 修改密码
                        // 循环输入直到密码满足复杂度要求
                        do {
                            if (!safe_input(password, sizeof(password), "请输入新密码(需包含大小写字母和数字，至少8位)：")) continue;
                        } while (!validate_password(password));
                        
                        rc = update_user_password(current_username, password);
                        if (rc == SQLITE_OK) {
                            printf("密码更新成功！\n");
                        } else {
                            printf("更新失败：发生错误！\n");
                        }
                        break;
                        
                    case 0: // 退出登录
                        is_logged_in = 0;
                        printf("已退出登录！\n");
                        break;
                        
                    default:
                        printf("无效选择，请重新输入！\n");
                }
            } 
            else {
                // 学生菜单
                printf("\n===== 学生菜单 =====\n");
                printf("当前用户: %s\n", current_username);
                printf("请选择操作：\n");
                printf("1. 查看个人信息\n");
                printf("2. 修改个人信息\n");
                printf("3. 修改密码\n");
                printf("0. 退出登录\n");
                printf("请输入选择：");

                if (scanf("%d", &choice) != 1) {
                    printf("无效输入！\n");
                    while (getchar() != '\n'); // 清空输入缓冲区
                    continue;
                }
                getchar(); // 消耗换行符

                switch (choice) {
                    case 1: // 查看个人信息
                        printf("\n个人信息：\n");
                        printf("用户名: %s\n", current_username);
                        printf("账号类型: 学生\n");
                        
                        // 查询并显示用户信息
                        stmt = NULL;
                        const char *sql = "SELECT user_info FROM Users WHERE username =?";
                        rc = sqlite3_prepare_v2(db, sql, -1, &stmt, 0);
                        if (rc == SQLITE_OK) {
                            sqlite3_bind_text(stmt, 1, current_username, -1, SQLITE_STATIC);
                            
                            if (sqlite3_step(stmt) == SQLITE_ROW) {
                                const unsigned char *info = sqlite3_column_text(stmt, 0);
                                printf("个人信息: %s\n", info ? (const char *)info : "无");
                            }
                            
                            sqlite3_finalize(stmt);
                        }
                        break;
                        
                    case 2: // 修改个人信息
                        if (!safe_input(user_info, sizeof(user_info), "请输入新的个人信息：")) continue;
                        
                        rc = update_user_info(current_username, user_info);
                        if (rc == SQLITE_OK) {
                            printf("个人信息更新成功！\n");
                        } else {
                            printf("更新失败：发生错误！\n");
                        }
                        break;
                        
                    case 3: // 修改密码
                        // 循环输入直到密码满足复杂度要求
                        do {
                            if (!safe_input(password, sizeof(password), "请输入新密码(需包含大小写字母和数字，至少8位)：")) continue;
                        } while (!validate_password(password));
                        
                        rc = update_user_password(current_username, password);
                        if (rc == SQLITE_OK) {
                            printf("密码更新成功！\n");
                        } else {
                            printf("更新失败：发生错误！\n");
                        }
                        break;
                        
                    case 0: // 退出登录
                        is_logged_in = 0;
                        printf("已退出登录！\n");
                        break;
                        
                    default:
                        printf("无效选择，请重新输入！\n");
                }
            }
        }
    }

    sqlite3_close(db);
    return 0;
}